package tool;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 按行写如某文件
 * @author chz
 *
 */
public class WriteTool {

	// 单例模式 start
	public static int count=0;
	private volatile static WriteTool instance = null;
	private BufferedWriter bw;
	private BufferedReader bf;
	
	private FileWriter fw;

	private WriteTool() {

	}

	public static WriteTool getInstance(String filepath) {  // someOne.txt
		if (instance == null) {
			synchronized (WriteTool.class) {// 1
				if (instance == null) {// 2
					instance = new WriteTool();// 3
				}
			}
		}

		try {
			instance.fw = new FileWriter(filepath, true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		instance.bw = new BufferedWriter(instance.fw);

		return instance;
	}

	public void write(String str) {
		
		try {
			instance.bw.write(str);
			instance.bw.newLine();
			
			count = count + 1;
			if(count == 1000){
				count=0;
				instance.bw.flush();
			}
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	

	public void close() {
		try {
			instance.bw.close();
			instance.fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		WriteTool instance = WriteTool.getInstance("/Users/chz/Desktop/test.txt");
		for(Integer i=0;i<1000;i++){
			instance.write(i.toString());
		}
		instance.close();
	}

}
